package com.etlmaster.executor.steps.func;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.etlmaster.executor.Step;
import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.utils.DataCollectionUtils;

/**
 * @author Wugf
 * @date 2016-03-08
 */
@StepInstruction("getVariable")
public class GetVariableApiStep extends Step {

	private static final String strType = "str", dateType = "date",
			mapType = "map", listType = "list", all = "all";
	private GetVariableApiStepMeta meta;
	
	public GetVariableApiStep(StepMeta meta) {
		super(meta);
		this.meta = (GetVariableApiStepMeta) meta;

	}

	@Override
	protected int handle() {

		String type = meta.getType();
		String name = meta.getVariablename();
		List<String> keys = addKeySet(type, name, meta.getVariables());
		printVariable(type, keys);
		return 0;
	}

	@Override
	public boolean stop() {
		// TODO Auto-generated method stub
		return false;
	}

	public static boolean isValidDate(String str, String sdf) {
		boolean convertSuccess = false;

		if (str.length() >= sdf.length()) {
			SimpleDateFormat format = new SimpleDateFormat(sdf);
			try {

				format.setLenient(false);
				format.parse((String) str.subSequence(0, sdf.length()));
				convertSuccess = true;
			} catch (ParseException e) {
				convertSuccess = false;
			}
		}
		return convertSuccess;
	}

	public void printVariable(String type, List keyList) {

		Map<String, Object> map = new HashMap<String, Object>();
		meta.log("INFO","当前类型{}的变量总共有：{}个", type, keyList.size()+"");

		for (int i = 0; i < keyList.size(); i++) {
			String classType = meta.getVariable((String) keyList.get(i))
					.getClass().toString();
			String variableType = DataCollectionUtils.getProperties(
					"quote");
			map.put("type", classType);
			map.put("ListQuote", "${变量名称[序号i].列表字段名称},实例：${" + keyList.get(i)
					+ "[0].column}");
			map.put("StringQuote", "${变量名称},实例：${" + keyList.get(i) + "}");
			map.put("MapQuote", "${变量名称.属性名称}，实例：${" + keyList.get(i)
					+ ".attribute}");
			variableType = meta.variableSubstitution(variableType, map);

			meta.log("INFO","名称：{}，值：{}", keyList.get(i).toString(),
					meta.getVariable((String) keyList.get(i)).toString());
			meta.log("INFO","使用方法：{}", variableType);
		}
	}

	public List<String> addKeySet(String type, String name,
			Map<String, Object> variables) {
		List<String> keys = new LinkedList<String>();
		Iterator<String> it = variables.keySet().iterator();

		while (it.hasNext()) {
			String key = (String) it.next();
			Object ob = variables.get(key);
			if (name != null && name.length() > 0 &&type.equals(all)) {
					if(key.contains(name)){
						keys.add(key);
					}
			} else {
				if (ob instanceof String) {
					if (isValidDate(ob.toString(), "yyyyMM")
							|| isValidDate(ob.toString(), "yyyy-MM")) {
						if ((type.equals(dateType) || type.equals(all))&&(name.length()==0||key.contains(name))) {
							keys.add(key);
						}
					} else {
						if ((type.equals(strType) || type.equals(all))&&(name.length()==0||key.contains(name))) {
							keys.add(key);
						}
					}
				} else if (ob instanceof Map) {
					if ((type.equals(mapType) || type.equals(all))&&(name.length()==0||key.contains(name))) {
						keys.add(key);
					}
				} else if (ob instanceof List) {
					if ((type.equals(listType) || type.equals(all))&&(name.length()==0||key.contains(name))) {
						keys.add(key);
					}
				}
			}
		}

		return keys;
	}

}
